import { useEffect, useState } from "react"
import {
  FlatList,
  Image,
  ImageStyle,
  ListRenderItem,
  TextStyle,
  View,
  ViewStyle,
} from "react-native"
import { router } from "expo-router"
import { Ionicons } from "@expo/vector-icons"

import { Card, Screen, Text } from "@/components"
import { useStores } from "@/models/helpers/useStores"
import { AgentModel, type AgentModel as AgentDescriptor } from "@/services/api/agents"
import { addAgent } from "@/services/api/conversations"
import { useAppTheme } from "@/theme/context"
import { $styles } from "@/theme/styles"
import type { ThemedStyle } from "@/theme/types"

export default function AgentsPage() {
  const { themed, theme } = useAppTheme()
  const { agentsStore } = useStores()

  const [data, setData] = useState<AgentDescriptor[]>(agentsStore?.models || [])

  useEffect(() => {
    setData(agentsStore?.models || [])
  }, [agentsStore?.models])

  useEffect(() => {
    // agentsStore.fetchModels()
  }, [])

  const spacingSm = theme.spacing.sm

  const handleModelPress = (model: AgentModel) => {
    if (__DEV__) {
      console.log(`Selected model: ${model}`)
    }
    addAgent({ model: model.model })
      .then((res: any) => {
        console.log("addmodel", res.data)
        router.push(`/chat/${model.model}/${res.data.data.conversation.conversationId}`)
      })
      .catch((err) => {
        console.error("Error adding agent:", err)
      })
  }

  const renderModelCard: ListRenderItem<AgentDescriptor> = ({ item, index }) => {
    return (
      <Card
        onPress={() => handleModelPress(item)}
        style={themed($cardContainer)}
        LeftComponent={
          <Image source={{ uri: item.iconUrl }} style={themed($cardImage)} resizeMode="cover" />
        }
        ContentComponent={
          <View>
            <Text weight="medium" size="md" text={item.model} />
            <Text numberOfLines={1} size="xxs" style={themed($cardDescription)} text={item.brief} />
            {/*{item.requestModalities && item.requestModalities.length > 0 ? (
              <Text
                size="xxs"
                style={themed($cardDescription)}
                text={`输入类型：${item.requestModalities.join(" / ")}`}
              />
            ) : null}*/}
          </View>
        }
        /*RightComponent={
          <View style={themed($rightComponentContainer)}>
            <Ionicons name="add-circle-outline" size={32} color="black" />
          </View>
        }*/
        accessibilityRole="button"
      />
    )
  }

  const keyExtractor = (item: AgentDescriptor) => item.model

  return (
    <Screen
      preset="fixed"
      safeAreaEdges={["top"]}
      style={themed($screen)}
      contentContainerStyle={$styles.flex1}
    >
      <FlatList
        data={data}
        renderItem={renderModelCard}
        keyExtractor={keyExtractor}
        contentContainerStyle={themed($gridContent)}
        showsVerticalScrollIndicator={false}
      />
    </Screen>
  )
}

const $screen: ThemedStyle<ViewStyle> = ({ colors }) => ({
  flex: 1,
})

const $gridContent: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingHorizontal: spacing.md,
  paddingTop: spacing.lg,
  paddingBottom: spacing.xxl,
})

const $cardContainer: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  flex: 1,
  gap: spacing.xxs,
  marginBottom: spacing.xs,
  backgroundColor: "transparent",
  borderWidth: 0,
})

const $cardImage: ThemedStyle<ImageStyle> = () => ({
  width: 60,
  height: 60,
  borderRadius: 30,
})

const $cardDescription: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
  marginTop: spacing.xs,
  lineHeight: 18,
})

const $rightComponentContainer: ThemedStyle<ViewStyle> = () => ({
  justifyContent: "center",
})
